using UnityEngine;
using DLib.BehaviorTree;
using DLib.BehaviorTree.Tasks;

/// <summary>
/// 守卫AI演示脚本
/// 
/// 需求描述：
/// 1. 正常情况下，守卫在两个哨所之间移动巡逻
/// 2. 巡逻过程中有一定概率停下来休息
/// 3. 巡逻过程中有一定概率给朋友发信息聊天
/// 4. 不管什么状态下，只要听到警报，马上就进入警戒状态
/// 5. 警戒状态下会寻找威胁源并准备战斗
/// 
/// 行为树结构：
/// - 根选择器（最高优先级）
///   ├── 警戒序列（听到警报时）
///   │   ├── 检查警报状态
///   │   ├── 进入警戒模式
///   │   ├── 寻找威胁源
///   │   └── 准备战斗
///   └── 正常巡逻选择器
///       ├── 休息序列（随机触发）
///       ├── 聊天序列（随机触发）
///       └── 巡逻序列（默认行为）
/// </summary>
public class GuardDemo : MonoBehaviour
{
    /// <summary>行为树组件引用</summary>
    public BehaviorTree behaviorTree;
    
    /// <summary>是否听到警报</summary>
    public bool isAlarmTriggered = false;
    
    /// <summary>当前哨所索引（0或1）</summary>
    public int currentPostIndex = 0;
    
    /// <summary>两个哨所的位置</summary>
    public Transform[] guardPosts = new Transform[2];
    
    /// <summary>休息概率（0-1之间）</summary>
    public float restProbability = 0.3f;
    
    /// <summary>聊天概率（0-1之间）</summary>
    public float chatProbability = 0.2f;
    
    /// <summary>巡逻速度</summary>
    public float patrolSpeed = 2f;
    
    /// <summary>是否正在移动</summary>
    public bool isMoving = false;
    
    /// <summary>目标位置</summary>
    private Vector3 targetPosition;
    
    /// <summary>警戒状态</summary>
    public bool isOnAlert = false;

    /// <summary>
    /// Unity Start方法
    /// 初始化守卫AI并创建行为树
    /// </summary>
    void Start()
    {
        // 创建行为树实例
        if (behaviorTree == null)
        {
            behaviorTree = new BehaviorTree();
        }

        // 初始化哨所位置（如果没有设置，使用默认位置）
        InitializeGuardPosts();
        
        // 创建守卫行为树
        CreateGuardBehaviorTree();
    }

    /// <summary>
    /// Unity Update方法
    /// 处理移动逻辑并手动更新行为树
    /// </summary>
    void Update()
    {
        // 处理移动逻辑
        if (isMoving && !isOnAlert)
        {
            MoveToTarget();
        }
        
        // 手动更新行为树
        if (behaviorTree.isRunning && behaviorTree.root != null)
        {
            NodeState state = behaviorTree.root.Evaluate();
            
            if (state != NodeState.Running)
            {
                behaviorTree.isRunning = false;
                Debug.Log($"Guard Behavior Tree completed with state: {state}");
            }
        }
    }

    /// <summary>
    /// 初始化哨所位置
    /// 如果没有手动设置哨所，则使用默认位置
    /// </summary>
    void InitializeGuardPosts()
    {
        if (guardPosts[0] == null)
        {
            // 创建哨所1
            GameObject post1 = new GameObject("GuardPost1");
            post1.transform.position = transform.position + Vector3.left * 5f;
            guardPosts[0] = post1.transform;
        }
        
        if (guardPosts[1] == null)
        {
            // 创建哨所2
            GameObject post2 = new GameObject("GuardPost2");
            post2.transform.position = transform.position + Vector3.right * 5f;
            guardPosts[1] = post2.transform;
        }
        
        // 设置初始目标位置
        targetPosition = guardPosts[currentPostIndex].position;
    }

    /// <summary>
    /// 创建守卫行为树
    /// 实现复杂的AI决策逻辑
    /// </summary>
    void CreateGuardBehaviorTree()
    {
        // 创建根选择器 - 最高优先级
        Selector rootSelector = new Selector();

        // 优先级1：警戒状态（最高优先级）
        // 不管什么状态下，只要听到警报就立即进入警戒状态
        Sequence alertSequence = new Sequence();
        alertSequence.AddChild(new CheckAlarmTask(this));
        alertSequence.AddChild(new LogTask("警报响起！进入警戒状态", 0.5f));
        alertSequence.AddChild(new AlertModeTask(this));
        alertSequence.AddChild(new SearchThreatTask(this));
        alertSequence.AddChild(new PrepareCombatTask(this));

        // 优先级2：正常巡逻行为（较低优先级）
        Selector normalBehaviorSelector = new Selector();
        
        // 休息行为（随机触发）
        Sequence restSequence = new Sequence();
        restSequence.AddChild(new RandomTask(restProbability));
        restSequence.AddChild(new LogTask("感觉有点累，休息一下", 0.5f));
        restSequence.AddChild(new RestTask(this));
        
        // 聊天行为（随机触发）
        Sequence chatSequence = new Sequence();
        chatSequence.AddChild(new RandomTask(chatProbability));
        chatSequence.AddChild(new LogTask("给朋友发个消息", 0.5f));
        chatSequence.AddChild(new ChatTask(this));
        
        // 巡逻行为（默认行为）
        Sequence patrolSequence = new Sequence();
        patrolSequence.AddChild(new LogTask("继续巡逻", 0.5f));
        patrolSequence.AddChild(new PatrolTask(this));

        // 添加所有正常行为到选择器
        normalBehaviorSelector.AddChild(restSequence);
        normalBehaviorSelector.AddChild(chatSequence);
        normalBehaviorSelector.AddChild(patrolSequence);

        // 添加警戒和正常行为到根选择器
        rootSelector.AddChild(alertSequence);
        rootSelector.AddChild(normalBehaviorSelector);

        // 设置根节点
        behaviorTree.SetRoot(rootSelector);
    }

    /// <summary>
    /// 移动到目标位置
    /// </summary>
    void MoveToTarget()
    {
        Vector3 direction = (targetPosition - transform.position).normalized;
        transform.position += direction * patrolSpeed * Time.deltaTime;
        
        // 检查是否到达目标
        if (Vector3.Distance(transform.position, targetPosition) < 0.5f)
        {
            isMoving = false;
            // 切换到下一个哨所
            currentPostIndex = (currentPostIndex + 1) % 2;
            targetPosition = guardPosts[currentPostIndex].position;
        }
    }

    /// <summary>
    /// 触发警报
    /// 用于测试警戒状态
    /// </summary>
    public void TriggerAlarm()
    {
        isAlarmTriggered = true;
        isOnAlert = true;
        Debug.Log("警报被触发！");
    }

    /// <summary>
    /// 解除警报
    /// </summary>
    public void ClearAlarm()
    {
        isAlarmTriggered = false;
        isOnAlert = false;
        Debug.Log("警报解除");
    }

    /// <summary>
    /// Unity OnGUI方法
    /// 显示守卫状态和控制界面
    /// </summary>
    void OnGUI()
    {
        // 创建GUI区域
        GUILayout.BeginArea(new Rect(10, 10, 350, 200));
        
        // 显示标题
        GUILayout.Label("守卫AI演示", GUI.skin.box);
        
        // 显示状态信息
        GUILayout.Label($"警报状态: {(isAlarmTriggered ? "触发" : "正常")}");
        GUILayout.Label($"警戒状态: {(isOnAlert ? "警戒中" : "正常")}");
        GUILayout.Label($"当前哨所: {currentPostIndex + 1}");
        GUILayout.Label($"正在移动: {isMoving}");
        GUILayout.Label($"AI状态: {behaviorTree.GetCurrentState()}");
        
        // 控制按钮
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("触发警报"))
        {
            TriggerAlarm();
        }
        if (GUILayout.Button("解除警报"))
        {
            ClearAlarm();
        }
        GUILayout.EndHorizontal();
        
        if (GUILayout.Button("重新开始"))
        {
            behaviorTree.ResetTree();
        }
        
        // 结束GUI区域
        GUILayout.EndArea();
    }
}

/// <summary>
/// 检查警报任务
/// 检查是否听到警报
/// </summary>
public class CheckAlarmTask : TaskNode
{
    private GuardDemo guard;

    public CheckAlarmTask(GuardDemo guard)
    {
        this.guard = guard;
    }

    protected override NodeState OnUpdate()
    {
        return guard.isAlarmTriggered ? NodeState.Success : NodeState.Failure;
    }
}

/// <summary>
/// 警戒模式任务
/// 进入警戒状态
/// </summary>
public class AlertModeTask : TaskNode
{
    private GuardDemo guard;
    private float startTime;

    public AlertModeTask(GuardDemo guard)
    {
        this.guard = guard;
    }

    protected override void OnStart()
    {
        startTime = Time.time;
        guard.isOnAlert = true;
        guard.isMoving = false; // 停止巡逻
    }

    protected override NodeState OnUpdate()
    {
        // 警戒模式持续2秒
        if (Time.time - startTime >= 2f)
        {
            return NodeState.Success;
        }
        return NodeState.Running;
    }

    protected override void OnStop()
    {
        // 警戒模式结束
    }
}

/// <summary>
/// 寻找威胁源任务
/// 在警戒状态下寻找威胁源
/// </summary>
public class SearchThreatTask : TaskNode
{
    private GuardDemo guard;
    private float startTime;

    public SearchThreatTask(GuardDemo guard)
    {
        this.guard = guard;
    }

    protected override void OnStart()
    {
        startTime = Time.time;
    }

    protected override NodeState OnUpdate()
    {
        // 寻找威胁源持续3秒
        if (Time.time - startTime >= 3f)
        {
            return NodeState.Success;
        }
        return NodeState.Running;
    }
}

/// <summary>
/// 准备战斗任务
/// 准备与威胁源战斗
/// </summary>
public class PrepareCombatTask : TaskNode
{
    private GuardDemo guard;
    private float startTime;

    public PrepareCombatTask(GuardDemo guard)
    {
        this.guard = guard;
    }

    protected override void OnStart()
    {
        startTime = Time.time;
    }

    protected override NodeState OnUpdate()
    {
        // 准备战斗持续2秒
        if (Time.time - startTime >= 2f)
        {
            // 战斗准备完成，解除警戒状态
            guard.isOnAlert = false;
            return NodeState.Success;
        }
        return NodeState.Running;
    }
}

/// <summary>
/// 休息任务
/// 守卫停下来休息
/// </summary>
public class RestTask : TaskNode
{
    private GuardDemo guard;
    private float startTime;

    public RestTask(GuardDemo guard)
    {
        this.guard = guard;
    }

    protected override void OnStart()
    {
        startTime = Time.time;
        guard.isMoving = false; // 停止移动
    }

    protected override NodeState OnUpdate()
    {
        // 休息持续3秒
        if (Time.time - startTime >= 3f)
        {
            return NodeState.Success;
        }
        return NodeState.Running;
    }

    protected override void OnStop()
    {
        guard.isMoving = true; // 休息结束，继续移动
    }
}

/// <summary>
/// 聊天任务
/// 守卫给朋友发信息聊天
/// </summary>
public class ChatTask : TaskNode
{
    private GuardDemo guard;
    private float startTime;

    public ChatTask(GuardDemo guard)
    {
        this.guard = guard;
    }

    protected override void OnStart()
    {
        startTime = Time.time;
        guard.isMoving = false; // 停止移动
    }

    protected override NodeState OnUpdate()
    {
        // 聊天持续2秒
        if (Time.time - startTime >= 2f)
        {
            return NodeState.Success;
        }
        return NodeState.Running;
    }

    protected override void OnStop()
    {
        guard.isMoving = true; // 聊天结束，继续移动
    }
}

/// <summary>
/// 巡逻任务
/// 守卫在两个哨所之间移动巡逻
/// </summary>
public class PatrolTask : TaskNode
{
    private GuardDemo guard;

    public PatrolTask(GuardDemo guard)
    {
        this.guard = guard;
    }

    protected override void OnStart()
    {
        guard.isMoving = true; // 开始移动
    }

    protected override NodeState OnUpdate()
    {
        // 巡逻任务持续5秒
        return NodeState.Success;
    }

    protected override void OnStop()
    {
        // 巡逻结束
    }
} 